<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue';
import categoryTree from '@/views/common/categoryTree'
import SingleUpload from '@/components/upload/singleUpload.vue'
import { saveAttrInfoApi, getAttrListApi, getAttrInfoApi, updateAttrInfoApi, deleteAttrApi } from '@/apis/pms/attribute.js'
import { Delete, EditPen, Search, Switch, Refresh } from '@element-plus/icons-vue'
import relateCategory from './components/relateCategory'


// 图片分类
const uploadType = "attribute"

// 搜索条件，参数名
const params = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  type: '',
  categoryId: 0,
})

const loading = ref(false)

// 提示框显示
const dialogFormVisible = ref(false)

// 获取属性列表
const attrData = ref({})
const getAttributeList = async () => {
  loading.value = true
  const res = await getAttrListApi(params);
  attrData.value = res.data;
  loading.value = false
}

// 表单数据
const attrForm = ref({})
const value = ref([])
let title = '';
const handleAddOrUpdate = async (id) => {
  if (id === null) {
    title = '添加属性'
    attrForm.value = {}
    value.value = []
    attrForm.value.status = 0;
    dialogFormVisible.value = true;
  } else {
    const res = await getAttrInfoApi(id);
    title = '修改属性'
    attrForm.value = res.data;
    value.value = res.data.value.split(";")
    dialogFormVisible.value = true;
  }
}

// 重置
const handleRefresh = () => {
  params.pageNum = 1;
  params.pageSize = 10;
  params.name = '';
  params.type = '';
  params.categoryId = 0;
  getAttributeList();
}

// 分页
const getAttrListPage = (currentIndex) => {
  params.pageNum = currentIndex;
  getAttributeList();
}

// 条件查询
const handleQuery = () => {
  getAttributeList();
}

// 点击取消
const singleUploadComponent = ref();
const handleCancel = () => {
  if (attrForm.value.id === null || attrForm.value.id === '' || attrForm.value.id === void 0) {
    if (attrForm.value.icon === null || attrForm.value.icon === '' || attrForm.value.icon === void 0) {
      dialogFormVisible.value = false;
    } else {
      // id为空,添加时点击取消，删除上传的图片
      singleUploadComponent.value.handleRemove();
      dialogFormVisible.value = false;
    }
  } else {
    // 修改点击取消，不能删除
    dialogFormVisible.value = false;
  }
}

// 修改状态
const updateStatus = (data) => {
  updateAttrInfoApi(data)
    .then(res => {
      if (res.code === 0) {
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        // 刷新数据
        getAttributeList()
      }
    })
}

// 点击确定
const handleConfirm = () => {
  // 添加
  attrForm.value.value = value.value.join(";")
  if (attrForm.value.id === null || attrForm.value.id === '' || attrForm.value.id === void 0) {
    saveAttrInfoApi(attrForm.value)
      .then(res => {
        if (res.code === 0) {
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          // 刷新数据
          getAttributeList();
          dialogFormVisible.value = false
        }
      })
  } else {
    // 修改
    updateAttrInfoApi(attrForm.value)
      .then(res => {
        if (res.code === 0) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          // 刷新数据
          getAttributeList()
          dialogFormVisible.value = false
        }
      })
  }
}

// 关联分类
const childRelateCategory = ref()
const handleAssociationCategory = async (id) => {
  await nextTick(() => {
    childRelateCategory.value.init(id);
  })
}

// 复选框事件
const ids = ref([])
const handleSelectionChange = (selection) => {
  ids.value = []
  selection.forEach(el => {
    ids.value.push(el.id)
  })
}

// 单个删除
const handleRemove = (id) => {
  ElMessageBox.confirm(
    '你确定要删除此属性吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      deleteAttrApi([id])
        .then(res => {
          if (res.code === 0) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
            getAttributeList()
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 批量删除
const handleRemoves = () => {
  if (ids.value.length === 0) {
    ElMessage({
      message: '没有要删除的数据',
      type: 'info',
    })
    return;
  }

  ElMessageBox.confirm(
    '你确定要删除这些属性吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      deleteAttrApi(ids.value)
        .then(res => {
          if (res.code === 0) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
            getAttributeList()
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

onMounted(() => getAttributeList())
</script>

<template>
  <div class="container" v-loading="loading">
    <el-row :gutter="10">
      <el-col :span="5">
        <categoryTree v-model:categoryId="params.categoryId" @refreshData="getAttributeList" />
      </el-col>

      <el-col :span="19">
        <el-row>
          <el-col :span="24" style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 10px;">
            <span style="display: inline-block;width: 60px;">属性名</span>
            <el-input v-model="params.name" placeholder="输入属性名进行查询" clearable style="width: 280px;" />
            <span style="display: inline-block;width: 70px;margin-left: 8px;">属性类型</span>
            <el-select v-model="params.type" clearable placeholder="请选择属性类型" style="width: 280px;">
              <el-option :key="0" label="规格属性" :value="0"/>
              <el-option :key="1" label="参数属性" :value="1"/>
            </el-select>
            <el-button type="primary" :icon="Search" style="margin-left: 10px;" @click="handleQuery">搜索</el-button>
            <el-button @click="handleRefresh" :icon="Refresh">重置</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 10px;">
            <el-button type="primary" plain @click="handleAddOrUpdate(null)">添加属性</el-button>
            <el-button type="danger" plain @click="handleRemoves">批量删除</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table :data="attrData.list" border @selection-change="handleSelectionChange" style="width: 100%;">
              <el-table-column type="selection" width="60" align="center" />
              <el-table-column prop="name" label="属性名" width="200" align="center" />
              <el-table-column label="属性值类型" width="150" align="center">
                <template v-slot="scope">
                  <el-tag style="font-size: 15px;">{{ scope.row.selectType === 0 ? '单选值' : '多选值' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="icon" label="属性图标" align="center" width="180">
                <template v-slot="scope">
                  <div style="height: 50px;"><img :src="scope.row.icon" style="height: 100%;"></div>
                </template>
              </el-table-column>
              <el-table-column label="属性值" align="center">
                <template v-slot="scope">
                  <el-tag type='success' style="font-size: 15px;">{{ scope.row.value }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="启用状态" width="150" align="center">
                <template v-slot="scope">
                  <el-switch v-model="scope.row.status" class="ml-2"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="0"
                    :inactive-value="1" @change="updateStatus(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="属性类型" width="150" align="center">
                <template v-slot="scope">
                  <el-tag style="font-size: 15px;">{{ scope.row.type === 0 ? '规格属性' : '参数属性' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="250" align="center">
                <template v-slot="scope">
                  <el-button type="primary" text size="small" :icon="Switch"
                    @click="handleAssociationCategory(scope.row.id)">关联</el-button>
                  <el-button type="primary" text size="small" :icon="EditPen" @click="handleAddOrUpdate(scope.row.id)">修改</el-button>
                  <el-button type="primary" text size="small" :icon="Delete"
                    @click="handleRemove(scope.row.id)" >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <div class="pageination">
          <el-pagination v-model:current-change="attrData.pageNum" :page-size="attrData.pageSize" background
            layout="prev, pager, next" :page-count="attrData.pages" @current-change="getAttrListPage" />
        </div>
      </el-col>
    </el-row>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="title" style="width: 35%;">
    <el-form :model="attrForm" style="width: 96%;" label-width="90px">
      <el-form-item label="属性名">
        <el-input v-model="attrForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="属性类型">
        <el-select v-model="attrForm.type" placeholder="选择属性类型">
          <el-option label="规格属性" :value='0' />
          <el-option label="参数属性" :value='1' />
        </el-select>
      </el-form-item>
      <el-form-item label="属性图标">
        <SingleUpload v-model:picture="attrForm.icon" :uploadType="uploadType" :width="60" :height="60"
          ref="singleUploadComponent"></SingleUpload>
      </el-form-item>
      <el-form-item label="属性值类型">
        <el-select v-model="attrForm.selectType" placeholder="选择值类型">
          <el-option label="单选值" :value='0' />
          <el-option label="多选值" :value='1' />
        </el-select>
      </el-form-item>
      <el-form-item label="参数值">
        <el-select v-model="value" multiple filterable :multiple-limit="attrForm.selectType === 0 ? 1 : 0" allow-create
          default-first-option :reserve-keyword="false" style="width: 100%;" placeholder="输入参数值" />
      </el-form-item>
      <el-form-item label="启用状态">
        <el-switch v-model="attrForm.status" class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="0" :inactive-value="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加关联 -->
  <relateCategory ref="childRelateCategory"></relateCategory>
</template>

<style scoped lang='scss'>
.continer {
  display: flex;
  width: 100%;

  .left {
    width: 20%;
    padding-right: 10px;
  }

  .right {
    width: 80%;

    .head {
      width: 100%;
      position: relative;
      height: 40px;

      .but {
        width: 45%;
        position: absolute;
        left: 0;
      }

      .search {
        width: 55%;
        position: absolute;
        text-align: end;
        right: 0;
      }
    }
  }
}
</style>